package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.xmlbeans.impl.jam.mutable.MElement;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.common.persistence.model.MentoringRelation;
import com.stylefeng.guns.modular.train.service.IMentoringRelationService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 师徒关系控制器
 *
 * @author fengshuonan
 * @Date 2018-01-29 11:30:37
 */
@Controller
@RequestMapping("/mentoringRelation")
public class MentoringRelationController extends BaseController {

    private String PREFIX = "/train/mentoringRelation/";

    @Autowired
    private IMentoringRelationService mentoringRelationService;
    @Autowired
    private IEmployeeService employeeService;
    /**
     * 跳转到师徒关系首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "mentoringRelation.html";
    }

    /**
     * 跳转到添加师徒关系
     */
    @RequestMapping("/mentoringRelation_add")
    public String mentoringRelationAdd() {
        return PREFIX + "mentoringRelation_add.html";
    }

    /**
     * 跳转到修改师徒关系
     */
    @RequestMapping("/mentoringRelation_update/{mentoringRelationId}")
    public String mentoringRelationUpdate(@PathVariable String mentoringRelationId, Model model) {
        MentoringRelation mentoringRelation = mentoringRelationService.selectById(mentoringRelationId);
        model.addAttribute("item",mentoringRelation);
        LogObjectHolder.me().set(mentoringRelation);
        return PREFIX + "mentoringRelation_edit.html";
    }

    /**
     * 获取师徒关系列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<MentoringRelation> mentoringRelations = mentoringRelationService.selectList(null);
            mentoringRelations.forEach(t->{
                if(t.getSignDate()!=null){
                    t.setStrSignDate(Const.df.format(t.getSignDate()));
                }
            });
            return mentoringRelations;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<MentoringRelation> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<MentoringRelation> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("master_emp_code",empCodes);

            if(min != null || max != null){
//            min = min == null ? 0.0 : min;
//            max = max == null ? 9999.0 : max;
//
//            nwWrapper.between("integral",min,max);
            }

            list = mentoringRelationService.selectList(nwWrapper);
        }

        list.forEach(t->{
            if(t.getSignDate()!=null){
                t.setStrSignDate(Const.df.format(t.getSignDate()));
            }
        });
        return list;
    }

    /**
     * 新增师徒关系
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(MentoringRelation mentoringRelation) {
        setResultCode(mentoringRelation);
        mentoringRelation.setDataOrigin(Const.IMPORT_TYPE_SYS);
        mentoringRelation.setCreateDate(new Date());
        mentoringRelationService.insert(mentoringRelation);
        mentoringRelationService.updateByMentoringRelationChange(mentoringRelation,Const.OPERATION_ADD);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除师徒关系
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String mentoringRelationId) {
        if(mentoringRelationId.contains(",")){
            List<String> ids = Arrays.asList(mentoringRelationId.split(","));
            for (String id : ids) {
                MentoringRelation mentoringRelation=mentoringRelationService.selectById(id);
                mentoringRelationService.deleteById(id);
                mentoringRelationService.updateByMentoringRelationChange(mentoringRelation,Const.OPERATION_DELETE);
            }
        }else{
            MentoringRelation mentoringRelation=mentoringRelationService.selectById(mentoringRelationId);
            mentoringRelationService.deleteById(mentoringRelationId);
            mentoringRelationService.updateByMentoringRelationChange(mentoringRelation,Const.OPERATION_DELETE);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改师徒关系
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(MentoringRelation mentoringRelation) {
        setResultCode(mentoringRelation);
        mentoringRelationService.updateById(mentoringRelation);
        mentoringRelationService.updateByMentoringRelationChange(mentoringRelation,Const.OPERATION_UPDATE);
        return super.SUCCESS_TIP;
    }

    /**
     * 师徒关系详情
     */
    @RequestMapping(value = "/detail/{mentoringRelationId}")
    @ResponseBody
    public Object detail(@PathVariable("mentoringRelationId") String mentoringRelationId) {
        return mentoringRelationService.selectById(mentoringRelationId);
    }

    private void setResultCode(MentoringRelation mentoringRelation){
        Map<String,String> protocalTermCodes = new HashMap<>();
        protocalTermCodes.put("一年","1");
        protocalTermCodes.put("两年","2");
        protocalTermCodes.put("三年","3");

        Map<String,String> examineResultCodes = new HashMap<>();
        examineResultCodes.put("合格","1");
        examineResultCodes.put("不合格","-1");

        if(!StringUtils.isEmpty(mentoringRelation.getExamineResult())){
            mentoringRelation.setExamineResultCode(examineResultCodes.get(mentoringRelation.getExamineResult()));
        }

        if(!StringUtils.isEmpty(mentoringRelation.getProtocalTerm())){
            mentoringRelation.setProtocalTermCode(protocalTermCodes.get(mentoringRelation.getProtocalTerm()));
        }
    }

    /**
     * 跳转到导入师徒关系
     */
    @RequestMapping("/mentoringRelation_import")
    public String mentoringRelationImport() {
        return PREFIX + "mentoringRelation_import.html";
    }

    /**
     * 导入师徒关系
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        Map<String,String> protocalTermCodes = new HashMap<>();
        protocalTermCodes.put("一年","1");
        protocalTermCodes.put("两年","2");
        protocalTermCodes.put("三年","3");

        Map<String,String> examineResultCodes = new HashMap<>();
        examineResultCodes.put("合格","1");
        examineResultCodes.put("不合格","-1");


        try {
            List<MentoringRelation> mentoringRelations = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), MentoringRelation.class, params);
            Date now = new Date();
            mentoringRelations.forEach(mentoringRelation -> {

                String protocalTerm = mentoringRelation.getProtocalTerm().trim();
                if(!StringUtils.isEmpty(protocalTerm)){
                    mentoringRelation.setProtocalTermCode(protocalTermCodes.get(protocalTerm));
                }
                String examineResult = mentoringRelation.getExamineResult();
                if(!StringUtils.isEmpty(examineResult)){
                    mentoringRelation.setExamineResultCode(examineResultCodes.get(examineResult));
                }

                mentoringRelation.setDataOrigin(Const.IMPORT_TYPE_XML);
                mentoringRelation.setCreateDate(now);
                mentoringRelationService.insert(mentoringRelation);
                //更新到分数
                mentoringRelationService.updateByMentoringRelationChange(mentoringRelation,Const.OPERATION_ADD);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return super.SUCCESS_TIP;
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<MentoringRelation> mentoringRelations= mentoringRelationService.selectList(null);
            mentoringRelations.forEach(item->{
                if("1".equals(item.getExamineResultCode())){
                    item.setIntegral(5.0);
                }else {
                    item.setIntegral(0.0);
                }
            });
            ExportParams exportParams=new ExportParams("师带徒积分统计表", "师带徒积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, MentoringRelation.class, mentoringRelations);
            OutputStream outputStream=response.getOutputStream();
            String fileName="师带徒积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
